package com.example.hao.day8_20;


import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private TextView tv_show;
    private AsyncTask asyncTask;
    private AlertDialog.Builder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        tv_show = findViewById(R.id.tv_show);

    }

    public void textLoadUseAsyncTask(View view) {

        String address = "http://192.168.3.159:8080/home/getWeChats.do?pageNum=1&pageCount=10";

        asyncTask = new AsyncTask();

        asyncTask.execute(address);

    }

    public class AsyncTask extends android.os.AsyncTask<String, Void, AsyncTaskData> {



        //第一个被执行的方法
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            builder = new AlertDialog.Builder(MainActivity.this);
            builder.setMessage("任务进行中..").create();

        }

        @Override
        protected AsyncTaskData doInBackground(String... strings) {
            Log.d(TAG, "doInBackground: "+strings[0]);
            String s = HttpUtils.get(strings[0]);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "doInBackground: "+s);
            Gson gson = new Gson();
            AsyncTaskData asyncTaskData = gson.fromJson(s, AsyncTaskData.class);

            return asyncTaskData;
        }
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }
        @Override
        protected void onPostExecute(AsyncTaskData asyncTaskData) {
            super.onPostExecute(asyncTaskData);

            tv_show.setText(asyncTaskData.toString());
        }

        @Override
        protected void onCancelled(AsyncTaskData asyncTaskData) {
            super.onCancelled(asyncTaskData);

            Toast.makeText(MainActivity.this, "任务取消", Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();

            Toast.makeText(MainActivity.this, "任务取消...", Toast.LENGTH_SHORT).show();

        }
    }

    @Override
    public void onBackPressed() {
        asyncTask.cancel(true);
        
//        super.onBackPressed();


    }
}
